package com.splashcard.net;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.splashcard.engine.SplashEngine;
import com.splashcard.message.GroupExecCallBackMessage;
import com.splashcard.monitor.IMonitorService;
import com.splashcard.monitor.MonitorInfoBean;
import com.splashcard.monitor.MonitorServiceImpl;

public class MechineServer {
	private final static Logger logger = Logger.getLogger(SplashServer.class
			.getName());
	private ServerSocket server;

	public void init(final int port) throws IOException {
		new Thread(new Runnable() {
			public void run() {
				try {
					server = new ServerSocket(port);
					while (true) {
						Socket socket = server.accept();
						invoke(socket);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

	public void terminal() throws IOException {
		server.close();
	}

	private static void invoke(final Socket socket) throws IOException {
		new Thread(new Runnable() {
			public void run() {
				try {
					final ObjectInputStream is = new ObjectInputStream(
							new BufferedInputStream(socket.getInputStream()));
					final ObjectOutputStream os = new ObjectOutputStream(
							socket.getOutputStream());
					Object obj = is.readObject();
					String order = (String) obj;
					if(order.equals("getMonitorInfo")){
						IMonitorService service = new MonitorServiceImpl();   
				        MonitorInfoBean monitorInfo = service.getMonitorInfoBean();   
						os.writeObject(monitorInfo);						
					}else{
						os.writeObject("unknown");
					}
					os.flush();
				} catch (IOException ex1) {
					logger.log(Level.SEVERE, null, ex1);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}
}
